package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    //处理订单支付超时--在业务上，超过15分钟未支付，代表超时了，需要修改状态
    @Scheduled(cron = "* 0/15 * * * ? ")  //每分钟触发一次
    public void doOverTimeOrder(){
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        //1.查询订单表（条件：未支付状态，下单时间），找出超时未支付的订单
        List<Orders> orders = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);

        //2.修改超时订单的状态未“已取消”
        if (orders != null && orders.size() > 0){
            orders.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason(MessageConstant.OVER_TIME_UNPAID);
                orderMapper.update(order);
            });
        }
    }

    @Scheduled(cron = "0 0 1 * * *")  //每天凌晨1点触发
    public void doDeliveryOrder(){
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        //处理订单一直派送--如果存在派送中的订单，需要将状态改为“已完成”
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);
        ordersList.forEach(order -> {
            order.setStatus(Orders.COMPLETED); //订单状态
            order.setDeliveryTime(LocalDateTime.now().minusHours(1)); //送达时间
            orderMapper.update(order);
        });
    }
}
